/**
 * 作者:hanbo
 * 日期:2019/1/1815:11
 * 描述:
 */
var map = L.map("map", {
    attributionControl: false,
    measureControl: true
});
var showPopup=false;

map.fitBounds([[39.937231, 118.983355], [40.803165, 120.000694]]);//调整地图范围
loadData();

//请求本地数据，绘制图形
function loadData() {
    loadBound();
    loadWall();
    loadPillars();
    loadPlot();
    loadDoor();
    loadStairs();
    loadLabel();
    map.on("zoomend ", function (e) {
        if (map.getZoom() > 11) {
            map.eachLayer(function (layer) {
                if (layer.isLabel) {
                    layer.setOpacity(1);
                }
            });
        } else {
            map.eachLayer(function (layer) {
                if (layer.isLabel) {
                    layer.setOpacity(0);
                }
            });
        }
    })
}

function loadWall() {
    $.get("data/wall.json", function (data, status) {
        if (status === "success") {
            var style = {
                weight: 3,
                color: "#BBFFFF",
                fillColor: "#FFFFFF",
                zIndex: 1
            };
            data.features.forEach(function (feature) {
                var latLngs = getCoordinate(feature.geometry.paths[0]);
                L.polyline(latLngs,
                    style
                ).addTo(map);
            });
        }
    });
}

function loadPillars() {
    $.get("data/pillars.json", function (data, status) {
        if (status === "success") {
            var style = {
                weight: 2,
                color: "#000000",
                fillColor: "#ABABAB",
                zIndex: 2
            };
            data.features.forEach(function (feature) {
                var latLngs = getCoordinate(feature.geometry.rings[0]);
                L.polygon(latLngs,
                    style
                ).addTo(map);
            });
        }
    });
}

function loadPlot() {
    $.get("data/plot.json", function (data, status) {
        if (status === "success") {
            var style = {
                weight: 2,
                color: "#FF0000",
                fillColor: "#FFA07A",
                zIndex: 4
            };
            data.features.forEach(function (feature) {
                var latLngs = getCoordinate(feature.geometry.rings[0]);
                L.polygon(latLngs,
                    style
                ).addTo(map);
            });
        }
    });
}

function loadBound() {
    $.get("data/bound.json", function (data, status) {
        if (status === "success") {
            // var style=mapEvent.style;
            data.features.forEach(function (feature) {
                var latLngs = getCoordinate(feature.geometry.rings[0]);
                L.polygon(latLngs,
                    {zIndex: 0}
                ).addTo(map);
            });
        }
    });
}

function loadDoor() {
    $.get("data/door.json", function (data, status) {
        if (status === "success") {
            var style = {
                weight: 1,
                color: "#EEEE00",
                fill: false,
                zIndex: 3
            };
            data.features.forEach(function (feature) {
                var latLngs = getCoordinate(feature.geometry.rings[0]);
                L.polygon(latLngs,
                    style
                ).addTo(map);
            });
        }
    });
}

function loadStairs() {
    $.get("data/stairs.json", function (data, status) {
        if (status === "success") {
            var style = {
                weight: 1,
                zIndex: 3
            };
            data.features.forEach(function (feature) {
                if (feature.attributes.type == "步梯") {
                    style.color = "#00FF00";
                    style.fillColor = "#4EEE94";
                } else {
                    style.color = "#4876FF";
                    style.fillColor = "#1E90FF";
                }
                var latLngs = getCoordinate(feature.geometry.rings[0]);
                var polygon = L.polygon(latLngs,
                    style
                ).addTo(map);

                var myIcon = L.divIcon({html: feature.attributes.name, iconSize: [50, 20]});
                var marker = L.marker(polygon.getCenter(), {icon: myIcon, opacity: 0, iconAnchor: [25, 10]});
                marker.isLabel = true;
                marker.addTo(map);
            });
        }
    });
}

function loadLabel() {
    $.get("data/point.json", function (data, status) {
        if (status === "success") {
            data.features.forEach(function (feature) {
                if (feature.attributes.name != " " && feature.attributes.type != "步梯" && feature.attributes.type != "电梯") {
                    var myIcon = L.divIcon({html: feature.attributes.name, iconSize: [50, 20]});
                    var marker = L.marker([feature.geometry.y, feature.geometry.x], {
                        icon: myIcon,
                        opacity: 0,
                        iconAnchor: [25, 10]
                    });
                    marker.isLabel = true;
                    marker.addTo(map);
                }
            });
        }
    });
}


/**
 * 将json坐标格式转换
 */
function getCoordinate(coordinates) {
    var coord = [];
    coordinates.forEach(function (coordinate) {
        coord.push([coordinate[1], coordinate[0]]);
    });
    return coord;
}

function clear() {
    map.eachLayer(function (layer) {
        if (layer.isPath) {
            map.removeLayer(layer)
        }
    });
}

function queryPath(point) {
    $.ajax({
        type: "GET",
        url: "http://localhost:8081/road?y1=" + point[0].lat + "&x1=" + point[0].lng + "&y2=" + point[1].lat + "&x2=" + point[1].lng,
        success: function (results) {
            var style1 = {
                style: function (e) {
                    return {
                        color: "#FF0000"
                    }
                }
            };
            var style2 = {
                style: function (e) {
                    return {
                        color: "#00FF00",
                        dashArray: "15, 10, 5, 10, 15"
                    }
                }
            };

            for (var i = 0; i < results.length; i++) {
                var layer;
                if (results[i].linetype == 1) {
                    layer = L.geoJSON(JSON.parse(results[i].st_asgeojson), style2).addTo(map);
                    if (i == 0) {
                    }
                } else {
                    var json = JSON.parse(results[i].st_asgeojson);
                    layer = L.geoJSON(json, style1).addTo(map);
                    if (json.coordinates.length > 2) {
                        if(map.distance([json.coordinates[0][1], json.coordinates[0][0]],[json.coordinates[1][1], json.coordinates[1][0]])<5000){
                            getLeftOrRight(
                                map.latLngToContainerPoint([json.coordinates[0][1], json.coordinates[0][0]])
                                , map.latLngToContainerPoint([json.coordinates[1][1], json.coordinates[1][0]])
                                , map.latLngToContainerPoint([json.coordinates[2][1], json.coordinates[2][0]])
                            )
                        }else {
                            showPopup=0;
                            map.closePopup();
                        }
                    }else {
                        showPopup=0;
                        map.closePopup();
                    }
                }

                layer.isPath = true;
            }

        },
        error: function (xhr, status, error) {
            console.log(error)
        }
    });
}

function getLeftOrRight(point1, point2, point3) {

    var vec1 = [point2.x - point1.x, point2.y - point1.y];
    var vec2 = [point1.x - point3.x, point1.y - point3.y];
    var a_b = (vec1[0] * vec2[0] + vec1[1] * vec2[1]);
    var moudle1 = getMoudle(vec1[0], vec1[1]);
    var moudle2 = getMoudle(vec2[0], vec2[1]);
    var degree = Math.acos(a_b / (moudle1 * moudle2));

    if (degree < 2.3) {
        if ((vec1[0] * vec2[1] - vec1[1] * vec2[0]) > 0) {//在右侧
            if(showPopup!=1){
                showPopup=1;
                L.popup()
                    .setLatLng(map.containerPointToLatLng(point2))
                    .setContent('<p>左转</p>')
                    .openOn(map);
            }

        } else {//在左侧
            if(showPopup!=2){
                showPopup=2;
                L.popup()
                    .setLatLng(map.containerPointToLatLng(point2))
                    .setContent('<p>右转</p>')
                    .openOn(map);
            }
        }
    }else {
        showPopup=0;
        map.closePopup();
    }
}

function getMoudle(x, y) {
    return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))
}